﻿using System;
using System.Threading;

namespace Homework_3
{
    //订阅器类
    class User
    {
        public void StartTick(MyClock myClock) 
        {
            Console.WriteLine("嘀咕事件被调用了！");
            myClock.TickEvent += myClock.TickCall;
        }
        public void StartAlarm(MyClock myClock)
        {
            Console.WriteLine("响铃事件被调用了！");
            myClock.AlarmEvent += myClock.AlarmCall;
            Console.WriteLine("输入响铃时间，例如13:23:10");
            myClock.SetAlarm(Console.ReadLine());
        }
        
        //执行
        static void Main(string[] args)
        {
            MyClock myClock = new MyClock();
            User user = new User();
            //订阅器启用嘀咕功能
            user.StartTick(myClock);
            //订阅器启用闹铃功能
            user.StartAlarm(myClock);
            myClock.TickCall();
            myClock.AlarmCall();
        }
    }

    

    //发布器类,使用多线程
    public class MyClock
    {
        private string setAlarmTime = "";
        private int saveSec = 61;
        //声明事件
        public delegate void Handler();
        public event Handler TickEvent;
        public event Handler AlarmEvent;
        //设置闹铃时间
        public void SetAlarm(string time)
        {
            setAlarmTime = time;
        }
        //每秒嘀咕一下
        private void Tick() {
            while (true)
            {
                int nowSec = System.DateTime.Now.Second;
                if (saveSec != nowSec)
                {
                    Console.WriteLine("嘀咕");
                    saveSec = nowSec;
                }
            }
            
        }
        public void TickCall()
        {
            Thread childTread = new Thread(()=>
            {
                Tick();
            });
            if (TickEvent!=null)
            {
                childTread.Start();
            } 
        }
        //到达设定时间后响铃
        private void Alarm()
        {
            while (true)
            {
                string timeNow = System.DateTime.Now.ToLongTimeString();
                if (setAlarmTime.Equals(timeNow))
                {
                    Console.WriteLine("闹钟响铃！！！！！！！！！");
                }
            }
        }
        public void AlarmCall()
        {
            Thread childThread1 = new Thread(() =>
                  {
                      Alarm();
                  });
            if (AlarmEvent!=null)
            {
                childThread1.Start();
            }
        }
    }
}
